package org.canaan.auth2.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractMybatisDao<T> {
	protected  Logger logger = LoggerFactory.getLogger(getClass());
	
	protected SqlSession sqlSession;	//sql连接会话
	protected  String nameSpace;		//mybatis 命名空间
	
	public AbstractMybatisDao(){
		if(getEntityType()!=null){
			nameSpace = getEntityType().getName();
		}
	}
	
	/**
	 * 取得当前实体的类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Class<T> getEntityType(){
		Type supperType = getClass().getGenericSuperclass();
		
		if(supperType instanceof ParameterizedType){
			Type[] paramTypes = ((ParameterizedType) supperType).getActualTypeArguments();
			if (paramTypes.length>0) {
				return (Class<T>) paramTypes[0];
			}
			logger.warn("{}不能确定实体类型",getClass());
		}
		logger.warn("{}未指定实体的类型",getClass());
		return null;
	}
	
	public SqlSession getSqlSession() {
		return sqlSession;
	}
	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}
}
